package net.wds.study.clazz.dao.impl;



import net.wds.study.clazz.dao.ClazzDao;
import net.wds.study.clazz.entity.Clazz;
import net.wds.study.clazz.utils.PageModel;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by gf on 2020/9/8.
 */
@Repository("clazzDao")
public class ClazzDaoImpl implements ClazzDao {

    @Resource(name = "sessionFactory")
    private SessionFactory sf;


    public Session getSession() {
        return sf.getCurrentSession();
    }

    public SessionFactory getSf() {
        return sf;
    }

    /**
     * @Author GongFan
     * @Description  班级信息分页查询
     * @Date 2020/9/8 19:57
     * @Param [startIndex, pageSize, clazzMajor, clazzYear, clazzLeader] 当前页起始索引   页条数   参数列表[专业  年级  班主任]
     * @return net.wds.utils.PageModel<net.wds.clazz.entity.Clazz>
     **/
    @Override
    public PageModel<Clazz> getPageByParams(Integer startIndex, Integer pageSize, String clazzMajor, String clazzYear, String clazzLeader) {

        PageModel<Clazz> pageModel = new PageModel<Clazz>();

        //判断pageSize值是否合法
        if (pageSize != null && pageSize > 0) {
            pageModel.setPageSize(pageSize);
        }

        List<Object> params = new ArrayList<>();

        //拼接hql语句
        StringBuilder hql = new StringBuilder("select c from Clazz c where 1=1 ");

        if (clazzMajor != null && !("".equals(clazzMajor))) {
            hql.append(" and c.clazzMajor like ?");
            params.add("%"+ clazzMajor.trim() +"%");
        }
        if (clazzYear != null && !("".equals(clazzYear))) {
            hql.append(" and c.clazzYear like ?");
            params.add("%"+clazzYear.trim()+"%");
        }

        if (clazzLeader != null && !("".equals(clazzLeader))) {
            hql.append(" and c.clazzLeader like ?");
            params.add("%"+clazzLeader.trim()+"%");
        }

        Query query = getSession().createQuery(hql.toString());

        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i, params.get(i));
        }
       //获取数据总条数
        int total = query.list().size();
        pageModel.setTotal(total);

        //获取总页数
        int pageTotal = total % pageModel.getPageSize() == 0 ? total / pageModel.getPageSize() : total / pageModel.getPageSize() + 1;

        pageModel.setPageTotal(pageTotal);

        //分页处理  当前页索引  每页数据条数
        query.setFirstResult(startIndex);
        query.setMaxResults(pageModel.getPageSize());
        //封装查询结果
        List<Clazz> list = query.list();
        pageModel.setPageData(list);
        return pageModel;
    }
}
